using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using DownloadMailTask.POP3Client;
using Microsoft.SqlServer.Dts.Runtime;
using DownloadMailTask.Interfaces;

namespace DownloadMailTask
{
    [DtsTask(
        DisplayName = "Download Mail Task",
        IconResource = "DownloadMailTask.icon.ico",
        UITypeName = "DownloadMailTask.DownloadMailTaskUI,DownloadMailTask,Version=1.0.0.0,Culture=neutral,PublicKeyToken=bb7cd1406e2749e1"
        )]
    public class DownloadMailTask : Task, IDownloadMailTask
    {
        private string _account;
        private bool _deleteMessage;
        private string _downloadPath;
        private string _fileExtension;
        private string _password;
        private int _port = 110;
        private string _serverAddress;
        private bool _unzip;
        private WriteOption _writeOption = WriteOption.DontOverwriteExisting;
        private bool _saveEmailFile;
        private string _fromFilter;

        [CategoryAttribute("General"), DisplayName("Delete Message")]
        public bool DeleteMessage
        {
            get { return _deleteMessage; }
            set { _deleteMessage = value; }
        }

        [CategoryAttribute("General"), DisplayName("Write Options")]
        public WriteOption WriteOptions
        {
            get { return _writeOption; }
            set { _writeOption = value; }
        }

        [CategoryAttribute("General"), DisplayName("Unzip Compressed Attachment")]
        public bool Unzip
        {
            get { return _unzip; }
            set { _unzip = value; }
        }

        [Category("Connection"), DisplayName("Server Address")]
        public string ServerAddress
        {
            get { return _serverAddress; }
            set { _serverAddress = value; }
        }

        [CategoryAttribute("Connection"), DisplayName("Port")]
        public int Port
        {
            get { return _port; }
            set { _port = value; }
        }

        [CategoryAttribute("Authentication"), DisplayName("User Name")]
        public string UserName
        {
            get { return _account; }
            set { _account = value; }
        }

        [CategoryAttribute("Authentication"), DisplayName("Password")]
        [PasswordPropertyText(true)]
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }

        [CategoryAttribute("General"), DisplayName("Attachment Extension")]
        public string FileAttachmentExtension
        {
            get { return _fileExtension; }
            set { _fileExtension = value; }
        }

        [CategoryAttribute("General"), DisplayName("Download Directory")]
        public string DownloadPath
        {
            get { return _downloadPath; }
            set { _downloadPath = value; }
        }

        [CategoryAttribute("General"), DisplayName("Save email file")]
        public bool SaveEmailFile
        {
            get { return _saveEmailFile; }
            set { _saveEmailFile = value; }
        }

        [CategoryAttribute("General"), DisplayName("Filter Senders")]
        public string FromFilter
        {
            get { return _fromFilter; }
            set { _fromFilter = value;}
        }

        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser,
                                              IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            POPClient client = new POPClient();
            MailDataReceiver receiver =
                new MailDataReceiver(componentEvents, client, _serverAddress, _port, _account, _password, _deleteMessage, _fileExtension, _unzip,
                                     _downloadPath, _writeOption, _saveEmailFile);

            try
            {
                receiver.Receive();
            }
            catch (Exception e)
            {
                componentEvents.FireError(0, "", e.Message, "", 0);
                return DTSExecResult.Failure;
            }

            return DTSExecResult.Success;
        }

        public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser,
                                               IDTSComponentEvents componentEvents, IDTSLogging log)
        {
            try
            {
                Dns.GetHostEntry(_serverAddress);
            }
            catch (ProtocolViolationException e)
            {
                componentEvents.FireError(0, "", "Invalid server address: " + e.Message, "", 0);
                return DTSExecResult.Failure;
            }

            try
            {
                ICSharpCode.SharpZipLib.Zip.FastZip dummy = new ICSharpCode.SharpZipLib.Zip.FastZip();
            }
            catch (DtsGenericException e)
            {
                componentEvents.FireError(0, "", "Unable to load ICsharpZipLib library", "", 0);
                return DTSExecResult.Failure;
            }

            if (!Directory.Exists(_downloadPath))
            {
                componentEvents.FireError(0, "", String.Format("Invalid download path {0}", _downloadPath), "", 0);
                return DTSExecResult.Failure;
            }

            return DTSExecResult.Success;
        }
    }
}